package com.bestplus.daqingapp.common.image;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import java.io.InputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import com.bestplus.daqingapp.common.util.ThreadPoolUtil;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.File;
import java.io.FileOutputStream;
import com.pgyersdk.crash.PgyCrashManager;

public class ImageUtilModule extends ReactContextBaseJavaModule {


    public ImageUtilModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "XPJImageUtil";
    }

    @ReactMethod
    public void saveImage(final String base64Content, final Promise promise) {

            ThreadPoolUtil.execute(new Runnable() {
                @Override
                public void run() {

                    try {
                        Bitmap bitmap = null;
                        if(base64Content.indexOf("http") >=0){
                           bitmap =  GetImageInputStream(base64Content);
                        }else {
                          byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
                          bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        }

                        File DCIM = Environment.getExternalStoragePublicDirectory("DCIM");

                        File cameraDir = new File(DCIM, "Camera");

                        if (!cameraDir.exists()) cameraDir.mkdirs();

                        String name = "IMG_" + bitmap.hashCode() + ".jpg";

                        File file = new File(cameraDir, name);

                        FileOutputStream out = new FileOutputStream(file);

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

                        //MediaStore.Images.Media.insertImage(getReactApplicationContext().getContentResolver(), file.getAbsolutePath(), name, null);

                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file));
                        getReactApplicationContext().sendBroadcast(intent);

                        Log.i("log", "saveImage: " + file.getAbsolutePath());

                        promise.resolve(file.getAbsolutePath());

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        reject(promise, ex);
                    }
                }
            });
    }

        /** 
     * 获取网络图片 
     * @param imageurl 图片网络地址 
     * @return Bitmap 返回位图 
     */  
    public Bitmap GetImageInputStream(String imageurl){  
        URL url;  
        HttpURLConnection connection=null;  
        Bitmap bitmap=null;  
        try {  
            url = new URL(imageurl);  
            connection=(HttpURLConnection)url.openConnection();  
            connection.setConnectTimeout(6000); //超时设置  
            connection.setDoInput(true);   
            connection.setUseCaches(false); //设置不使用缓存  
            InputStream inputStream=connection.getInputStream();  
            bitmap=BitmapFactory.decodeStream(inputStream);  
            inputStream.close();  
        } catch (Exception e) {  
            PgyCrashManager.reportCaughtException(getReactApplicationContext(), e);  
        }  
        return bitmap;  
    } 

    private void reject(Promise promise, Exception ex) {
        promise.reject(null, ex.getMessage());
    }

       @ReactMethod
    public void uploadError(final String errorMsg, final Promise promise) {
        PgyCrashManager.reportCaughtException(getReactApplicationContext(), new Exception(errorMsg));
        promise.resolve(errorMsg);
    }

}
